package com.nail.post.utils;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailUtils {
    public static String myEmailAccount = "910940173@qq.com";
    public static String myEmailSMTPHost = "smtp.qq.com";
    public static String myEmailPassword = "gbinnbytnwkrbfia";//口令,QQ邮箱是输入授权码，在qq邮箱设置, 里用验证过的手机发送短信获得，不含空格,此处用密码无用

    public static void sendEmail(String to,String code) throws MessagingException {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol","smtp");
        props.setProperty("mail.smtp.host",myEmailSMTPHost);////发件人的邮箱的 SMTP 服务器地址
        props.setProperty("mail.smtp.auth","true");//需要进行验证


        // 开启 SSL 安全连接(qq邮箱需要开启ssl连接)
        final String smtpPort = "465";
        props.setProperty("mail.smtp.port", smtpPort);
        props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.socketFactory.port", smtpPort);

        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {

                return new PasswordAuthentication(myEmailAccount,myEmailPassword);
            }
        });

        session.setDebug(true);
            //创建邮件对象
        Message message = new MimeMessage(session);
        //设置发件人地址
        message.setFrom(new InternetAddress(myEmailAccount));
        //设置收件人地址
        message.setRecipient(Message.RecipientType.TO,new InternetAddress(to));
        //设置邮件主题
        message.setSubject("来自蜗牛之家的激活邮件");
        message.setContent("<h1>来自蜗牛之家的激活邮件，激活请点击以下连接：</h1>" +
                "<h3><a href='http://localhost:8080/RegisterServlet?code="+code+"'>" +
                "http://localhost:8080/javamail/ActiveServlet?code="+code+"</h3>","text/html;charset=UTF-8");
        //发送邮件
        Transport.send(message);





    }
}
